##************************* 将编译器 compile options 转换成 nvcc options
function(CUDA_CONVERT_FLAGS EXISTING_TARGET)
    get_property(old_flags TARGET ${EXISTING_TARGET} PROPERTY INTERFACE_COMPILE_OPTIONS)
    if(NOT "${old_flags}" STREQUAL "")
        string(REPLACE ";" "," CUDA_flags "${old_flags}")
        set_property(TARGET ${EXISTING_TARGET} PROPERTY INTERFACE_COMPILE_OPTIONS
            "$<$<BUILD_INTERFACE:$<COMPILE_LANGUAGE:CXX>>:${old_flags}>$<$<BUILD_INTERFACE:$<COMPILE_LANGUAGE:CUDA>>:-Xcompiler=${CUDA_flags}>"
            )
    endif()
endfunction()


##************************* 额外复制 CUDA DLL to binary dir;
# 默认只 copy 64 位的 DLL
function(my_cp_cuda_dlls target)
    if(NOT CMAKE_CUDA_COMPILER)
        message(WARNING "CMAKE_CUDA_COMPILER not found")
        return()
    endif()

    # 查找 CUDA 运行时 DLL
    find_file(CUDA_RUNTIME_DLL
        # NAMES cudart64_*.dll cudart32_*.dll
        NAMES cudart64_*.dll
        PATHS "${CUDAToolkit_LIBRARY_DIR}/bin"
        DOC "CUDA runtime DLL"
    )

    message("[cuda dlls] CUDAToolkit_LIBRARY_DIR => ${CUDAToolkit_LIBRARY_DIR}")
    message("[cuda dlls] CUDA_RUNTIME_DLL => ${CUDA_RUNTIME_DLL}")

    if(CUDA_RUNTIME_DLL)
        add_custom_command(TARGET ${target} POST_BUILD
            COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CUDA_RUNTIME_DLL}" $<TARGET_FILE_DIR:${target}>
            COMMENT "Copying CUDA runtime DLL to build directory"
        )
    endif()

    # 复制其他常见的 CUDA DLL
    if(FALSE)
    foreach(CUDA_LIB_NAME cublas cufft curand cusolver cusparse nvrtc)
        find_file(CUDA_${CUDA_LIB_NAME}_DLL
            # NAMES ${CUDA_LIB_NAME}64_*.dll ${CUDA_LIB_NAME}32_*.dll
            NAMES ${CUDA_LIB_NAME}64_*.dll
            PATHS "${CMAKE_CUDA_TOOLKIT_ROOT_DIR}/bin"
            DOC "CUDA ${CUDA_LIB_NAME} DLL"
        )

        if(CUDA_${CUDA_LIB_NAME}_DLL)
            add_custom_command(TARGET ${target} POST_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CUDA_${CUDA_LIB_NAME}_DLL}" $<TARGET_FILE_DIR:${target}>
                COMMENT "Copying CUDA ${CUDA_LIB_NAME} DLL to build directory"
            )
        endif()
    endforeach()
    endif()

endfunction()